<template>
  <div class="search-suggestion">
    <van-cell
      v-for="(item, index) in suggestions"
      :key="index"
      icon="search"
      @click="$emit('input', item)"
    >
      <div slot="title" v-html="highlight(item)"></div>
    </van-cell>
  </div>
</template>

<script>
// 引入搜索联想的接口
import { getSearchSuggestions } from "@/api/search.js";
// 按需加载 把使用的成员打包到结果中
import { debounce } from "lodash";
export default {
  name: "SearchSuggestion",
  components: {},
  props: {
    value: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      suggestions: [], //联想建议数据列表
    };
  },
  computed: {},
  watch: {
    value: {
      //防抖
      handler: debounce(function (newval) {
        // value发生变化变化就调用联想函数
        this.loadSearchSuggestions(newval);
      }, 300),
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    async loadSearchSuggestions(q) {
      try {
        const { data } = await getSearchSuggestions(q);
        this.suggestions = data.data.options;
      } catch (err) {
        this.$toast("请求搜索联想失败请稍后重试");
      }
    },
    highlight(text) {
      const highlightStr = `<span class="active">${this.value}</span>`;
      //  正则表达式
      //  如果要写变量  手动new RegExp
      // 参数1 匹配模式字符串 会根据这个字符串创建正则对象
      // 参数2 匹配模式
      const reg = new RegExp(this.value, "gi");
      return text.replace(reg, highlightStr);
    },
  },
};
</script>

<style scoped lang="less">
.search-suggestion {
  /deep/.active {
    color: #3296fa;
  }
}
</style>
